package com.ahpu.jym.messagealert.ui;

import java.util.Enumeration;

import javax.microedition.pim.Contact;
import javax.microedition.pim.PIM;
import javax.wireless.messaging.TextMessage;

import com.ahpu.jym.messagealert.tools.OptionsData;
import com.ahpu.jym.messagealert.tools.SmsWork;
import com.ahpu.jym.messagealert.tools.Tools;

import resource.localResource;

import net.rim.blackberry.api.mail.Address;
import net.rim.blackberry.api.pdap.BlackBerryContact;
import net.rim.blackberry.api.pdap.BlackBerryContactList;
import net.rim.device.api.system.ApplicationDescriptor;
import net.rim.device.api.system.ApplicationManager;
import net.rim.device.api.system.ApplicationManagerException;
import net.rim.device.api.system.Characters;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.TouchEvent;
import net.rim.device.api.ui.Ui;
import net.rim.device.api.ui.UiEngine;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.EditField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.SeparatorField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.PopupScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;

public class MessageAlertDailog extends PopupScreen {

	public static boolean closed;
	/** 地址 **/
	String address;
	/** 内容 **/
	String message;
	/** 主题 **/
	String subject;
	/** name **/
	String name = "";
	/** 文本消息 **/
	TextMessage m;
	/** 地址 显示 **/
	LabelField addressField;
	/** 消息内容显示 **/
	EditField messageField;

	/** 是否邮件 **/
	boolean email = false;

	/** 获取当前Application **/
	ApplicationDescriptor current = ApplicationDescriptor
			.currentApplicationDescriptor();

	/**
	 * 
	 * <h4>Title:</h4>
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @param email
	 *            是否邮件
	 * @param address
	 *            地址
	 * @param message
	 *            消息
	 * @param subject
	 *            主题
	 */
	public MessageAlertDailog(boolean email, String address, String message,
			String subject) {

		super(new VerticalFieldManager(Manager.VERTICAL_SCROLL));
		this.address = address;
		this.message = message;
		this.email = email;
		this.subject = subject;

		addressField = new LabelField(Search(address), Field.NON_FOCUSABLE);
		addressField.setFont(Font.getDefault());

		messageField = new EditField(EditField.READONLY);
		messageField.setText(message);
		messageField.setFont(Font.getDefault());

		add(addressField);
		add(new SeparatorField());
		add(messageField);
		if (OptionsData.load().getShowButton() == 0) {
			HorizontalFieldManager btnHFM = new HorizontalFieldManager(
					Field.USE_ALL_WIDTH);

			ButtonField replyButton = new ButtonField(
					Tools.getResString(localResource.Reply),
					ButtonField.CONSUME_CLICK);
			replyButton.setChangeListener(new FieldChangeListener() {
				public void fieldChanged(Field field, int context) {
					close();
					reply();
				}
			});
			btnHFM.add(replyButton);

			ButtonField forwardButton = new ButtonField(
					Tools.getResString(localResource.Forward),
					ButtonField.CONSUME_CLICK);
			forwardButton.setChangeListener(new FieldChangeListener() {

				public void fieldChanged(Field field, int context) {
					close();
					forward();
				}
			});
			btnHFM.add(forwardButton);

			ButtonField closeButton = new ButtonField(
					Tools.getResString(localResource.Close),
					ButtonField.CONSUME_CLICK);
			closeButton.setChangeListener(new FieldChangeListener() {

				public void fieldChanged(Field field, int context) {
					close();
				}
			});
			btnHFM.add(closeButton);

			add(new SeparatorField());
			add(btnHFM);
		}

	}

	/**
	 * 
	 * <h4>Title:</h4>
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @param email
	 *            是否邮件
	 * @param address
	 *            地址
	 * @param message
	 *            消息
	 * @param subject
	 *            主题
	 */
	public MessageAlertDailog(boolean email, Address address, String message,
			String subject) {

		super(new VerticalFieldManager(Manager.VERTICAL_SCROLL));
		this.address = address.getAddr();
		this.message = message;
		this.email = email;
		this.name = address.getName();
		this.subject = subject;

		addressField = new LabelField(
				address.getName() == null ? address.getAddr()
						: address.getName() + "\n" + subject,
				Field.NON_FOCUSABLE);
		addressField.setFont(Font.getDefault());

		messageField = new EditField(EditField.READONLY);
		messageField.setText(message);
		messageField.setFont(Font.getDefault());

		add(addressField);
		add(new SeparatorField());
		add(messageField);
		// TODO
		if (OptionsData.load().getShowButton() == 0) {
			HorizontalFieldManager btnHFM = new HorizontalFieldManager(
					Field.USE_ALL_WIDTH);

			ButtonField replyButton = new ButtonField(
					Tools.getResString(localResource.Reply),
					ButtonField.CONSUME_CLICK);
			replyButton.setChangeListener(new FieldChangeListener() {
				public void fieldChanged(Field field, int context) {
					close();
					reply();
				}
			});
			btnHFM.add(replyButton);

			ButtonField forwardButton = new ButtonField(
					Tools.getResString(localResource.Forward),
					ButtonField.CONSUME_CLICK);
			forwardButton.setChangeListener(new FieldChangeListener() {

				public void fieldChanged(Field field, int context) {
					close();
					forward();
				}
			});
			btnHFM.add(forwardButton);

			ButtonField closeButton = new ButtonField(
					Tools.getResString(localResource.Close),
					ButtonField.CONSUME_CLICK);
			closeButton.setChangeListener(new FieldChangeListener() {

				public void fieldChanged(Field field, int context) {
					close();
				}
			});
			btnHFM.add(closeButton);

			add(new SeparatorField());
			add(btnHFM);
		}

	}

	/**
	 * 
	 * @param address
	 *            地址
	 * @param message
	 *            消息
	 * @param showButton
	 *            显示按钮
	 */
	public MessageAlertDailog(final String address, String message,
			boolean showButton) {
		super(new VerticalFieldManager(Manager.VERTICAL_SCROLL));
		this.address = address;
		this.message = message;

		addressField = new LabelField(Search(address), Field.NON_FOCUSABLE);
		addressField.setFont(Font.getDefault());

		messageField = new EditField(EditField.READONLY);
		messageField.setText(message);
		messageField.setFont(Font.getDefault());

		add(addressField);
		add(new SeparatorField());
		add(messageField);

		if (showButton) {
			HorizontalFieldManager btnHFM = new HorizontalFieldManager(
					Field.USE_ALL_WIDTH);

			ButtonField replyButton = new ButtonField(
					Tools.getResString(localResource.Reply),
					ButtonField.CONSUME_CLICK);
			replyButton.setChangeListener(new FieldChangeListener() {
				public void fieldChanged(Field field, int context) {
					close();
					reply();
				}
			});
			btnHFM.add(replyButton);

			ButtonField forwardButton = new ButtonField(
					Tools.getResString(localResource.Forward),
					ButtonField.CONSUME_CLICK);
			forwardButton.setChangeListener(new FieldChangeListener() {

				public void fieldChanged(Field field, int context) {
					close();
					forward();
				}
			});
			btnHFM.add(forwardButton);

			ButtonField closeButton = new ButtonField(
					Tools.getResString(localResource.Close),
					ButtonField.CONSUME_CLICK);
			closeButton.setChangeListener(new FieldChangeListener() {

				public void fieldChanged(Field field, int context) {
					close();
				}
			});
			btnHFM.add(closeButton);

			add(new SeparatorField());
			add(btnHFM);
		}

	}

	/*
	 * 关闭
	 * 
	 * @see net.rim.device.api.ui.Screen#close()
	 */
	public void close() {
		UiEngine uiEngine = Ui.getUiEngine();
		uiEngine.popScreen(this);
		// OptionsData data = OptionsData.load();
		// data.setPush(true);
		// data.commit();

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * net.rim.device.api.ui.Screen#touchEvent(net.rim.device.api.ui.TouchEvent)
	 */
	protected boolean touchEvent(TouchEvent mes) {

		String[] args = { "", address, message, subject };
		ApplicationManager appMan = ApplicationManager.getApplicationManager();
		ApplicationDescriptor current = ApplicationDescriptor
				.currentApplicationDescriptor();

		close();

		if (email) {
			args[0] = "M_R";
		} else {
			args[0] = "S_R";
		}

		ApplicationDescriptor descriptor = new ApplicationDescriptor(current,
				args);
		try {
			appMan.runApplication(descriptor);
		} catch (ApplicationManagerException e) {
			e.printStackTrace();
		}

		return true;
	}

	protected boolean keyChar(char key, int status, int time) {

		switch (key) {

		case Characters.ESCAPE:
		case Characters.LATIN_SMALL_LETTER_D:
		case Characters.LATIN_SMALL_LETTER_K:
			close();
			return true;

		case Characters.LATIN_SMALL_LETTER_R:
		case Characters.ENTER:
			close();
			reply();

			// Repaly();
			return true;

		case Characters.LATIN_SMALL_LETTER_F:
			close();

			forward();
			return true;

		case Characters.LATIN_SMALL_LETTER_M:
			close();
			mark();
			return true;
		default:
			break;
		}

		return super.keyChar(key, status, time);
	}

//	protected boolean navigationClick(int status, int time) {
//		// TODO Auto-generated method stub
//		close();
//		reply();
//		return true;
//	}

	private String Search(String address) {
		// TODO Auto-generated method stub

		// String addressName = address.substring(6); //sms://:0
		String addressName = address;// sms://
		try {
			BlackBerryContactList list = (BlackBerryContactList) PIM
					.getInstance()
					.openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE);

			Enumeration myEnum = list.itemsByPhoneNumber(address);

			while (myEnum.hasMoreElements()) {
				Object o = myEnum.nextElement();
				if (o instanceof BlackBerryContact) {
					BlackBerryContact c = (BlackBerryContact) o;

					String[] name = c.getStringArray(Contact.NAME, 0);
					String loacl = System.getProperty("microedition.locale")
							.substring(0, 2);
					if ("zh".equals(loacl)) {
						addressName = (name[Contact.NAME_FAMILY] == null ? ""
								: name[Contact.NAME_FAMILY])
								+ (name[Contact.NAME_GIVEN] == null ? ""
										: name[Contact.NAME_GIVEN]);
					} else {
						addressName = (name[Contact.NAME_GIVEN] == null ? ""
								: name[Contact.NAME_GIVEN])
								+ " "
								+ (name[Contact.NAME_FAMILY] == null ? ""
										: name[Contact.NAME_FAMILY]);
					}

				}
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}

		if (addressName.indexOf("sms://") > -1) {
			addressName = address.substring(6);
		}

		return addressName;

	}

	private void reply() {

		if (OptionsData.load().getGomessages() == 0) {
			SmsWork.Reply();
		} else {

			String[] args = { "", address, message, subject, name };
			ApplicationManager appMan = ApplicationManager
					.getApplicationManager();
			// ApplicationDescriptor current = ApplicationDescriptor
			// .currentApplicationDescriptor();
			if (email) {
				args[0] = "M_R";
			} else {
				args[0] = "S_R";
			}

			ApplicationDescriptor descriptor = new ApplicationDescriptor(
					current, args);
			try {
				appMan.runApplication(descriptor, true);
				appMan.requestForeground(appMan.getProcessId(descriptor));
			} catch (ApplicationManagerException e) {
				e.printStackTrace();
			}
		}
	}

	private void mark() {
		SmsWork.mark();
	}

	private void forward() {

		if (OptionsData.load().getGomessages() == 0) {
			SmsWork.Forward();
		} else {

			String[] args = { "", address, message, subject };
			ApplicationManager appMan = ApplicationManager
					.getApplicationManager();
			// ApplicationDescriptor current = ApplicationDescriptor
			// .currentApplicationDescriptor();
			if (email) {
				args[0] = "M_F";
			} else {
				args[0] = "S_F";
			}

			ApplicationDescriptor descriptor1 = new ApplicationDescriptor(
					current, args);
			try {
				appMan.runApplication(descriptor1, true);
				appMan.requestForeground(appMan.getProcessId(descriptor1));
			} catch (ApplicationManagerException e) {
				e.printStackTrace();
			}
		}
	}

}
